package nix.dom4j;

import java.io.FileOutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jUtils {

	/**
	 * 获得Document对象
	 * 
	 * @param url
	 * @return
	 */
	public static Document getDocument(String url) {
		try {
			// 获得解析器实例
			SAXReader reader = new SAXReader();
			// 解析XML获得文档实例
			Document document = reader.read(url);
			return document;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Document回写文件
	 * 
	 * @param url
	 * @param document
	 */
	public static void writeXML(String url, Document document) {
		try {
			// 设置输出格式
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileOutputStream(url), format);
			// 内存回写文件
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
